package abe;

import java.io.File;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

public class Parser {
	
 

	public  SearchableTreeNode parse(File sample) {
		Pattern pat = Pattern.compile("clientConnectionID=(.*?),time");

		SearchableTreeNode treeRoot = new SearchableTreeNode(new SearchableTreeNodeUserData(sample.getAbsolutePath()));
		for(String line : new TextFile(sample.getAbsolutePath())){
			if (line.contains("DistantClientConnection")||line.contains("DistantServerConnection")){
				Matcher mat = pat.matcher(line);
				if (mat.find()){
					String connectionDetail = mat.group(1);
					SearchableTreeNode connectionNode = null;
					if (line.contains("DistantClientConnection"))
						connectionNode = new SearchableTreeNode(new SearchableTreeNodeUserData("DistantClientConnection"));
					else
						connectionNode = new SearchableTreeNode(new SearchableTreeNodeUserData("DistantServerConnection"));
					treeRoot.add(connectionNode);
					parseConnectionDetails(connectionNode, connectionDetail);	
					
				}
				
			}
			
		}
		      
		return treeRoot;
	}

	private  void parseConnectionDetails(SearchableTreeNode root ,String line) {
		//System.out.println(line);
		Pattern openBracketPat = Pattern.compile("[\\[|\\]]");
		Pattern nextTextPat = Pattern.compile("(.*?)[\\[|\\]]");
		
		Matcher mat = openBracketPat.matcher(line);
		Stack<SearchableTreeNode> stack = new Stack();
		
		stack.add(root);
		while ( mat.find()){
			String bracket = mat.group();
			int bracketPos = mat.start();
			if (bracket.equals("[")){
				Matcher nextMat = nextTextPat.matcher(line.subSequence(mat.end(), line.length()));
				if (nextMat.find()){
					//System.out.println(line);
					SearchableTreeNode child1 = new SearchableTreeNode(new SearchableTreeNodeUserData(nextMat.group(1)));
					stack.lastElement().add(child1);
					stack.add(child1);
				}
					
			}else if (bracket.equals("]")){
				stack.pop();
			}
		}		
	}

}
